package com.wwj.study.observer.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wuweijun
 * @Date: 2018/11/20 16:09
 */
public class EventLisenter {

    protected Map<Enum, Event> eventMap = new HashMap<>();

    //添加监听方法 传入：需要监听的类型，观察者对象，观察者回调方法
    public void addLisenter(Enum eventType, Object traget, Method callback) {
        eventMap.put(eventType, new Event(traget, callback));
    }

    private void trigger(Event event) {
        event.setSource(this);
        event.setTime(System.currentTimeMillis());

        Method method = event.getCallback();
        try {
            //执行观察者回调方法
            method.invoke(event.getTarget(), event);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void trigger(Enum call) {
        if (!eventMap.containsKey(call)) {
            return;
        }

        Event event= eventMap.get(call);
        event.setTrigger(call.toString());

        trigger(event);
    }
}
